package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.remark.domain.po.LikedStat;
import com.tianji.remark.mapper.LikedStatMapper;
import com.tianji.remark.service.ILikedStatService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞统计表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-26
 */
@Service
public class LikedStatServiceImpl extends ServiceImpl<LikedStatMapper, LikedStat> implements ILikedStatService {



    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RabbitMqHelper rabbitMqHelper;
    /**
     * 修改点赞数量
     *
     * @param dto
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void updateLikedTimes(LikeRecordFormDTO dto) {
//        //判断是否为第一次点赞
//        LikedStat one = this.lambdaQuery()
//                .eq(LikedStat::getBizId, dto.getBizId())
//                .eq(LikedStat::getBizType, dto.getBizType())
//                .one();
//        if (one == null){
//            one = new LikedStat();
//            one.setBizId(dto.getBizId());
//            one.setBizType(dto.getBizType());
//            one.setLikedTimes(dto.getLiked() ? 1 : 0);
//            this.save(one);
//        }else {
//            //修改点赞数量
//            this.lambdaUpdate()
//                    .eq(LikedStat::getBizId, dto.getBizId())
//                    .eq(LikedStat::getBizType, dto.getBizType())
//                    .setSql(dto.getLiked() ? "liked_times = liked_times + 1" : "liked_times = liked_times - 1")
//                    .update();
//        }
//        //利用mq通知业务层更新点赞数量
//        LikedStat byId = this.getById(one.getBizId());
//        rabbitTemplate.send(
//                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
//                StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, dto.getBizId()),
//                new Message(new LikedTimesDTO(dto.getBizId(), byId.getLikedTimes()).toString().getBytes()));
//    }


    /**
     * 修改点赞数量
     *
     * @param bizType
     * @param msg
     */
    @Override
    public void updateLikedTimes(String bizType, List<LikedTimesDTO> msg) {
        // 1.更新本地数据库
        List<Long> bizIds = msg.stream().map(LikedTimesDTO::getBizId).collect(Collectors.toList());
        // 1.1.查询旧数据
        List<LikedStat> oldStats = lambdaQuery().in(LikedStat::getBizId, bizIds).list();
        Map<Long, LikedStat> oldStatMap = new HashMap<>(0);
        if(CollUtils.isNotEmpty(oldStats)) {
            oldStatMap = oldStats.stream().collect(Collectors.toMap(LikedStat::getBizId, Function.identity()));
        }
        // 1.2.处理为PO
        List<LikedStat> list = new ArrayList<>(msg.size());
        for (LikedTimesDTO dto : msg) {
            // 判断bizId是否已经存在
            LikedStat stat = oldStatMap.get(dto.getBizId());
            if(stat == null){
                // 不存在，新增
                stat = new LikedStat();
                stat.setBizId(dto.getBizId());
                stat.setLikedTimes(dto.getLikedTimes());
                stat.setBizType(bizType);
            }else{
                // 已经存在，需要更新
                stat.setLikedTimes(dto.getLikedTimes());
            }
            list.add(stat);
        }
        // 1.3.批处理
        saveOrUpdateBatch(list);

        // 2.发送MQ消息
        rabbitMqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType),
                msg);
    }
}
